<template>
  <div class="cart-box">
    <div class="container">
      <!-- 面包屑 -->
      <XtxBread>
        <XtxBreadItem to="/">首页</XtxBreadItem>
        <XtxBreadItem>购物车</XtxBreadItem>
      </XtxBread>
      <template v-if="validList.length !== 0">
        <div class="cart">
          <table>
            <thead>
              <tr>
                <th width="120">
                  <XtxCheckbox v-model="checkBoxList" @change="changCheckbox(!checkBoxList)">全选</XtxCheckbox>
                </th>
                <th width="400">商品信息</th>
                <th width="220">单价</th>
                <th width="180">数量</th>
                <th width="180">小计</th>
                <th width="140">操作</th>
              </tr>
            </thead>
            <!-- 有效商品 -->
            <tbody>
              <tr v-for="i in validList" :key="i.skuId">
                <td><XtxCheckbox v-model="i.selected" @change="radioBox(i.skuId, i.selected)" /></td>
                <td>
                  <div class="goods">
                    <RouterLink to="/">
                      <img :src="i.picture" alt="" />
                    </RouterLink>
                    <div>
                      <p class="name ellipsis">{{ i.name }}</p>
                      <p class="attr">{{ i.attrsText }}</p>
                    </div>
                  </div>
                </td>
                <td class="tc">
                  <p>&yen;{{ i.nowPrice }}</p>
                  <p>
                    比加入时降价<span class="red">&yen;{{ i.price - i.nowPrice }}</span>
                  </p>
                </td>
                <td class="tc">
                  <XtxNumbox :min="1" :max="i.stock" v-model="i.count" @change="updataCount(i.skuId, i.count)" />
                </td>
                <td class="tc">
                  <p class="f16 red">&yen;{{ (i.nowPrice * 100 * i.count) / 100 }}</p>
                </td>
                <td class="tc">
                  <p><a href="javascript:;">移入收藏夹</a></p>
                  <p><a class="green" href="javascript:;" @click="delCart(i.skuId)">删除</a></p>
                  <p><a href="javascript:;">找相似</a></p>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!-- 操作栏 -->
        <div class="action">
          <div class="batch">
            <XtxCheckbox v-model="checkBoxList" @change="changCheckbox(!checkBoxList)">全选</XtxCheckbox>
            <a href="javascript:;">删除全部商品</a>
          </div>
          <div class="total">
            共 {{ validList.length }} 件商品，已选择 {{ countNum }} 件，商品合计：
            <span class="red">{{ moneyTotal }}</span>
            <XtxButton type="primary" @click="settle">下单结算</XtxButton>
          </div>
        </div>
      </template>
      <CartNone v-else></CartNone>
    </div>
  </div>
</template>

<script>
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { computed, ref, onMounted } from 'vue'
import Confirm from 'erabbit-ui/packages/components/Confirm'
import Message from 'erabbit-ui/packages/components/Message'
import CartNone from './component/cart-none.vue'
export default {
  components: {
    CartNone
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const validList = computed(() => store.getters['cart/validList'])
    // 全选操作
    const checkBoxList = computed(() => {
      return store.getters['cart/checkBoxList']
    })
    const changCheckbox = Boolean => {
      store.dispatch('cart/checkboxList', Boolean)
    }

    // 删除操作
    const delCart = async skuId => {
      try {
        await Confirm({ title: '温馨提示!', text: '亲,您确定要删除商品吗?' })
        store.dispatch('cart/delCartList', skuId)
        Message({ type: 'success', text: '已成功删除商品。' })
      } catch (error) {
        Message({ type: 'success', text: '已取消删除操作。' })
      }
    }

    // 单选操作
    const radioBox = (skuId, selected) => {
      store.dispatch('cart/radioBoxList', { skuId, selected })
    }

    // 选中商品数
    const countNum = computed(() => {
      const num = ref(0)
      store.getters['cart/validList'].forEach(item => {
        if (item.selected === true) {
          num.value++
        }
      })
      return num.value
    })
    // 选中商品总金额
    // 先筛选出已勾选的，在计算总价格
    const moneyTotal = computed(() => {
      return (
        store.getters['cart/validList']
          .filter(item => item.selected === true)
          .reduce((p, c) => {
            return p + c.nowPrice * 100 * c.count
          }, 0) / 100
      )
    })

    // 修改商品数量
    const updataCount = (skuId, count) => {
      store.dispatch('cart/countNumber', { skuId, count })
    }
    onMounted(() => {
      store.dispatch('cart/getCartList')
    })
    // 下单结算
    // 1.判断是否勾选商品
    // 2.判断是否登录，登录过直接通过，没有登录还是跳转结算，因为后面要加拦截,且会记录你登录后需要跳转的地址
    // 3.添加访问权限控制，以user开头的路径都是需要登录权限
    // 4.登录完需要回跳到结算页
    const settle = async () => {
      const token = store.state.user.profile.token
      if (countNum.value === 0) return Message({ type: 'error', text: '请至少选择一件商品！' })
      if (token) {
        router.push('/user/checkout')
      } else {
        await Confirm({ title: '温馨提示!', text: '亲，您还没有登录，是否跳转到登录页进行登录?' })
        router.push('/user/checkout')
      }
    }
    return {
      validList,
      countNum,
      checkBoxList,
      moneyTotal,
      delCart,
      radioBox,
      changCheckbox,
      settle,
      updataCount
    }
  }
}
</script>

<style lang="less" scoped>
.cart {
  background: #fff;
  color: #666;
  table {
    border-spacing: 0;
    border-collapse: collapse;
    line-height: 24px;
    th,
    td {
      padding: 10px;
      border-bottom: 1px solid #f5f5f5;
      &:first-child {
        text-align: left;
        padding-left: 45px;
        color: #999;
      }
      th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
      }
    }
    .goods {
      display: flex;
      align-items: center;
      img {
        width: 100px;
        height: 100px;
      }
      div {
        width: 280px;
        font-size: 16px;
        padding-left: 10px;
        .attr {
          font-size: 14px;
          color: #999;
        }
      }
    }
    .tc {
      text-align: center;
      .xtx-numbox {
        margin: 0 auto;
        width: 120px;
      }
    }
    .red {
      color: var(--price-color);
    }
    .green {
      color: var(--xtx-color);
    }
    .f16 {
      font-size: 16px;
    }
  }
}
.action {
  background: #fff;
  margin-top: 20px;
  height: 80px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;
  .xtx-checkbox {
    color: #999;
    margin-left: 15px;
  }
  a {
    margin-left: 30px;
  }
  .red {
    font-size: 18px;
    margin-right: 20px;
    font-weight: bold;
  }
}
.tit {
  color: #666;
  font-size: 16px;
  font-weight: normal;
  line-height: 50px;
}
</style>
